/** */
package com.hotau.account;

import org.json.JSONException;
import org.json.JSONObject;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.hotau.Executable;
import com.hotau.HotauActivity;
import com.hotau.HotauConstants;
import com.hotau.R;
import com.hotau.member.service.MemberService;
import com.hotau.util.DialogUtil;
import com.hotau.util.HttpRequestAsynTask;
import com.hotau.util.HttpUtil;
import com.hotau.util.ValidateUtils;

/**
 * 找回支付密码
 * 
 * @author fengweili</br>1.0
 * @author liujia (liujia9234@126.com)1.1 2011-12-9 下午02:49:05
 * @version 1.1
 *          <ul>
 *          <li>1.0 创建</li>
 *          <li>1.1 实现具体的功能</li>
 *          </ul>
 */
public class FindPasswordFragment extends Fragment implements OnClickListener {

	public static final int LOST_PAY_VERIFY_PWD_SUBMIT = 1;
	public static final int LOST_PAY_CHANAGE_LOAD = 2;
	private TextView pay_lost_tv_phonenum = null;
	private EditText pay_lost_et_phone_checkcode = null;
	private EditText pay_lost_et_password = null;
	private EditText pay_lost_et_verify_password = null;
	private Button pay_lost_btn_checkcode_resend = null;
	private Button pay_lost_btn_submit = null;
	String guid = "";
	/**
	 * 异步请求Task
	 */
	HttpRequestAsynTask lost_pay_pwd_checkcode_task = null; // 获取支付密码校验码
	HttpRequestAsynTask lost_pay_pwd_check_code = null;// 验证校验码
	HttpRequestAsynTask lost_pay_pwd_task = null; // 修改支付密码

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onActivityCreated(savedInstanceState);
		initAllWidget();
		initAllEvent();
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		return inflater
				.inflate(R.layout.account_pay_lost_pwd, container, false);
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.account_lost_btn_checkcode_resend:
			StringBuffer sb = new StringBuffer();
			sb.append("Form:userCode="
					+ pay_lost_tv_phonenum.getText().toString());
			sb.append(";terminalCode=" + HotauConstants.getTerminalCode(getActivity()));
			sb.append(";type=3");
			lost_pay_pwd_checkcode_task = new HttpRequestAsynTask(getActivity()) {
				@Override
				protected void doPostExecute(String result) {
					// TODO Auto-generated method stub
					try {
						JSONObject data = new JSONObject(result);
						if (data != null && data.getInt("result") == 1) {
							// 获取效验码成功
							// pay_lost_et_phone_checkcode.setText(data.getString("checkCode"));
							pay_lost_btn_checkcode_resend
									.setBackgroundResource(R.drawable.account_pay_lost_btn_bg_sendcode_wait);
							pay_lost_btn_checkcode_resend.setEnabled(false);
							guid = data.getString("guid");
							new Thread(new Runnable() {
								@Override
								public void run() {
									// TODO Auto-generated method stub
									int i = 61;
									while (i > 0) {
										Message msg = new Message();
										msg.what = LOST_PAY_CHANAGE_LOAD;
										msg.getData().putString("text",
												(--i) + "秒后重发");
										lostPayHander.sendMessage(msg);
										if (i == 1) {
											lostPayHander.postDelayed(
													new Runnable() {
														@Override
														public void run() {
															pay_lost_btn_checkcode_resend
																	.setText("");
															pay_lost_btn_checkcode_resend
																	.setBackgroundResource(R.drawable.account_pay_lost_btn_bg_sendcode);
															pay_lost_btn_checkcode_resend
																	.setEnabled(true);
														}
													}, 1000);
											break;
										}
										try {
											Thread.sleep(1000);
										} catch (InterruptedException e) {
											// TODO Auto-generated catch block
											e.printStackTrace();
										}
									}
								}
							}).start();

						} else {
							// 获取效验码失败
							DialogUtil.showDialog(getActivity(), "",
									data.getString("errorMsg"));
						}
					} catch (JSONException e) {
						// TODO Auto-generated catch block
						DialogUtil.showDialog(getActivity(), "", "获取校验码数据出错 ");
					}
				}
			};
			lost_pay_pwd_checkcode_task.execute(
					HotauConstants.MEMBER_GET_CHECK_CODE_URL, sb.toString(),
					HttpUtil.UTF8_ENCODING);
			break;
		case R.id.account_pay_lost_btn_submit:
			if("".equals(guid.trim())){
				DialogUtil.showDialog(getActivity(), "", "验证码不存在或已经失效,请重新获取");
				return;
			}
			if("".equals(pay_lost_et_phone_checkcode.getText().toString().trim())){
				DialogUtil.showDialog(getActivity(), "", "请输入验证码");
				return;
			}
			if( !(pay_lost_et_password.getText().length() >=8 && pay_lost_et_password.getText().length() <= 20)){
				DialogUtil.showDialog(getActivity(), "", "支付密码必须是8-20个字符");
				return;
			}
			if( !(pay_lost_et_verify_password.getText().length()>=8 && pay_lost_et_verify_password.getText().length()<= 20)){
				DialogUtil.showDialog(getActivity(), "", "确认支付密码必须是8-20个字符");
				return;
			}
			if( !pay_lost_et_password.getText().toString().equals(pay_lost_et_verify_password.getText().toString())){
				DialogUtil.showDialog(getActivity(), "", "两次输入支付密码不一致");
				return;
			}
			if (!ValidateUtils.isLetteric(pay_lost_et_password.getText().toString().trim().substring(0, 1)))
            {
                DialogUtil.showDialog(getActivity(), "", "密码第一位必须为字母");
                return;
            }
            if (!ValidateUtils.isNumberLetteric(pay_lost_et_password.getText().toString().trim()))
            {
                DialogUtil.showDialog(getActivity(), "", "密码必须为字母和（或）数字的组合");
                return;
            }
			
			StringBuilder sb_submit = new StringBuilder();
			sb_submit.append("Form:userCode=" + pay_lost_tv_phonenum.getText());
			sb_submit.append(";guid=" + guid);
			sb_submit.append(";checkCode="+ pay_lost_et_phone_checkcode.getText());
			sb_submit.append(";terminalCode=" + HotauConstants.getTerminalCode(getActivity()));
			sb_submit.append(";type=" + 3);
			lost_pay_pwd_check_code = new HttpRequestAsynTask(getActivity()) {

				@Override
				protected void doPostExecute(String result) {
					// TODO Auto-generated method stub
					try {
						JSONObject data = new JSONObject(result);
						if (data != null && data.getInt("result") == 1) {
							lostPayHander.sendEmptyMessage(LOST_PAY_VERIFY_PWD_SUBMIT);
						} else {
							// 失败
//							csmbpActivity.pushFragment("信息提示",new MessagePromptFragment(false, data.getString("errorMsg")));
							DialogUtil.showDialog(getActivity(), "", data.getString("errorMsg"));
									
						}
					} catch (JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			};
			lost_pay_pwd_check_code.execute(
					HotauConstants.MEMBER_VALIDATE_CHECK_CODE_URL,
					sb_submit.toString(), HttpUtil.UTF8_ENCODING);
			break;
		default:
			break;
		}
	}

	/**
	 * 初始化所有控件
	 */
	public void initAllWidget() {
	    
		pay_lost_tv_phonenum = (TextView) getActivity().findViewById(
				R.id.account_pay_lost_tv_phonenum);
		JSONObject data = MemberService.getUserInfo(getActivity());
		
		if (data != null) {
            try {
                String phonenumber = data.getString("accName");
                pay_lost_tv_phonenum.setText(phonenumber);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
		
		pay_lost_et_phone_checkcode = (EditText) getActivity().findViewById(
				R.id.account_pay_lost_et_phone_checkcode);
		pay_lost_et_password = (EditText) getActivity().findViewById(
				R.id.account_pay_lost_et_password);
		pay_lost_et_verify_password = (EditText) getActivity().findViewById(
				R.id.account_pay_lost_et_verify_password);
		pay_lost_btn_submit = (Button) getActivity().findViewById(
				R.id.account_pay_lost_btn_submit);
		pay_lost_btn_checkcode_resend = (Button) getActivity().findViewById(
				R.id.account_lost_btn_checkcode_resend);

	}

	/**
	 * 初始化所有事件
	 */
	public void initAllEvent() {
		pay_lost_btn_checkcode_resend.setOnClickListener(this);
		pay_lost_btn_submit.setOnClickListener(this);
	}

	// 消息处理Hander
	public Handler lostPayHander = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case LOST_PAY_VERIFY_PWD_SUBMIT:
				// 重置支付密码(resetLoginPassword)
				StringBuilder sb_verify_submit = new StringBuilder();
				sb_verify_submit.append("Form:token="
						+ MemberService.getToken(getActivity()));
				sb_verify_submit.append(";newPwd="
						+ pay_lost_et_password.getText());
				sb_verify_submit.append(";confirmPwd="
						+ pay_lost_et_verify_password.getText());
				sb_verify_submit.append(";terminalCode=" + HotauConstants.getTerminalCode(getActivity()));
				lost_pay_pwd_task = new HttpRequestAsynTask(getActivity()) {

					@Override
					protected void doPostExecute(String result) {
						// TODO Auto-generated method stub
						try {
							JSONObject data = new JSONObject(result);
							if (data != null && data.getInt("result") == 1) {
								// 找回支付密码成功
//								csmbpActivity.pushFragment("信息提示",new MessagePromptFragment(true,"修改支付密码成功"));
								DialogUtil.showDialog(getActivity(), "", "修改支付密码成功", new Executable()
                                {
                                    
                                    @Override
                                    public void execute()
                                    {
                                        // TODO Auto-generated method stub
                                        ((HotauActivity)getActivity()).popFragment();
                                    }
                                });
								
								
							} else {
								// 找回支付密码失败
//								csmbpActivity.pushFragment("信息提示",new MessagePromptFragment(false, data.getString("errorMsg")));
								DialogUtil.showDialog(getActivity(), "", data.getString("errorMsg"));
							}
						} catch (JSONException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}
				};
				lost_pay_pwd_task.execute(
						HotauConstants.ACCOUNT_RESET_PAY_PWD_URL,
						sb_verify_submit.toString(), HttpUtil.UTF8_ENCODING);
				break;
			case LOST_PAY_CHANAGE_LOAD:
				String text = msg.getData().getString("text");
				pay_lost_btn_checkcode_resend.setText(text);
				break;
			default:
				break;
			}

		}
	};

}
